// @flow
import React, { Component } from 'react'
import { Input, Row, Col, Button, Select } from 'antd'
import styles from './eventLog.css'
import AgGrid from 'components/AgGrid'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import moment from 'moment'
import Pagination from 'components/Pagination'
const Option = Select.Option

type Props = {}
type States = {
  deviceData: Array<any>,
  columnDefs: Array<Object>,
  eventType: Array<string>,
  owner: Array<string>,
  status: Array<string>,
  pageSize: number,
  current: number,
  total: number,
  rowData: Array<any>,
  searchInfo: Object<any>
}
class EventLog extends Component {
  props: Props
  state: States
  searchQuery: string
  searchInfo: Object
  getData: Function
  onPageChange: Function
  getDeviceData: Function
  handleEventType: Function
  handleStatus: Function
  handleOwner: Function
  handleSearch: Function
  handleEventName: Function
  getFillterData: Function
  constructor (props: Props) {
    super(props)
    this.searchInfo = {
      eventName: '',
      deviceName: '',
      eventType: '',
      owner: '',
      status: ''
    }
    this.state = {
      deviceData: [],
      eventType: [],
      owner: [],
      status: [],
      pageSize: 20,
      current: 1,
      total: 0,
      rowData: [],
      searchInfo: {
        eventType: '事件类型',
        owner: '负责人',
        status: '状态'
      },
      columnDefs: [
        {
          headerName: '事件名称',
          field: 'eventName',
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '事件类型',
          field: 'eventType',
          cellStyle: {
            padding: '8px'
          }
        }, {
          headerName: '设备编号',
          field: 'deviceNo',
          cellStyle: {
            padding: '8px'
          }
        }, {
          headerName: '设备名称',
          field: 'deviceName',
          cellStyle: {
            padding: '8px'
          }
        }, {
          headerName: '开始时间',
          field: 'startTime',
          cellStyle: {
            padding: '8px'
          },
          cellRenderer: (params) => {
            return moment(params.data.startTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
          }
        },
        {
          headerName: '结束时间',
          field: 'endTime',
          cellStyle: {
            padding: '8px'
          },
          cellRenderer: (params) => {
            return moment(params.data.endTime, 'YYYY-MM-DDTHH:mm:ss.SSSZ').format('YYYY-MM-DD HH:mm:ss')
          }
        },
        {
          headerName: '负责人',
          field: 'owner',
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '处理方法',
          field: 'dealMethod',
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '状态',
          field: 'status',
          cellStyle: {
            padding: '8px'
          }
        },
        {
          headerName: '详细',
          field: 'detail',
          cellStyle: {
            padding: '8px'
          }
        }
      ]
    }
    this.searchQuery = ''
    this.getData = this.getData.bind(this)
    this.onPageChange = this.onPageChange.bind(this)
    this.getDeviceData = this.getDeviceData.bind(this)
    this.handleEventType = this.handleEventType.bind(this)
    this.handleStatus = this.handleStatus.bind(this)
    this.handleOwner = this.handleOwner.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.handleEventName = this.handleEventName.bind(this)
    this.handleDeviceName = this.handleDeviceName.bind(this)
    this.getFillterData = this.getFillterData.bind(this)
  }
  getFillterData () {
    universalFetch(`${__SERVICE_API__}device/events?pageNum=1&pageSize=1000&orderBy=update_time desc`)
       .then(res => res.json())
       .then((json) => {
         if (json.code !== 200000) {
           throw new Error(JSON.stringify({ code: json.code, message: json.message }))
         }
         // 过滤数组内重复的元素以及空元素
         let eventType = (Array.from(new Set(json.result.map(item => item.eventType)))).filter(item => item)
         let owner = (Array.from(new Set(json.result.map(item => item.owner)))).filter(item => item)
         let status = (Array.from(new Set(json.result.map(item => item.status)))).filter(item => item)
         eventType.unshift('全部')
         owner.unshift('全部')
         status.unshift('全部')
         this.setState({
           eventType,
           owner,
           status
         })
       })
       .catch((error) => {
         handleFetchError(error)
         console.error(error)
       })
  }
  getData (page: number, pageSize: number, filterQuery: string) {
    const { deviceData } = this.state
    const filterQuerys = filterQuery ? filterQuery : ''
    universalFetch(`${__SERVICE_API__}device/events?pageNum=${page}&pageSize=${pageSize}&orderBy=update_time desc${filterQuerys}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({ code: json.code, message: json.message }))
        }
        this.setState({
          current: page,
          total: json.pageInfo.total,
          rowData: json.result.map((d, i) => {
            const deviceD = deviceData.filter((dd) => dd.id === d.deviceId)
            if (deviceD.length > 0) {
              d['deviceName'] = deviceD[0].name || ''
              d['deviceNo'] = deviceD[0].deviceNo || ''
            }
            return d
          })
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  onPageChange (page: number, pageSize: number) {
    this.getData(page, pageSize, this.searchQuery)
  }

  componentWillMount () {
    this.getDeviceData()
    this.getFillterData()
  }
  getDeviceData () {
    universalFetch(`${__SERVICE_API__}device/devices?pageSize=20000`)
    .then((res) => res.json())
    .then((json) => {
      if (json.code !== 200000) {
        throw new Error(JSON.stringify({ code: json.code, message: json.message }))
      }
      this.setState({
        deviceData: json.result
      }, () => {
        this.getData(this.state.current, this.state.pageSize)
      })
    })
    .catch((error) => {
      console.error(error)
    })
  }
  handleEventType (value: any) {
    if (value.slice(0, 2) === '全部') {
      this.searchInfo.eventType = ''
      return
    }
    this.searchInfo.eventType = value
  }
  handleOwner (value: any) {
    if (value.slice(0, 2) === '全部') {
      this.searchInfo.owner = ''
      return
    }
    this.searchInfo.owner = value
  }
  handleStatus (value: any) {
    if (value.slice(0, 2) === '全部') {
      this.searchInfo.status = ''
      return
    }
    this.searchInfo.status = value
  }
  handleSearch () {
    let { eventName, deviceName, eventType, owner, status } = this.searchInfo
    this.searchQuery = `&eventName=${eventName}&deviceName=${deviceName}&eventType=${eventType}&owner=${owner}&status=${status}`
    this.getData(this.state.current, this.state.pageSize, this.searchQuery)
  }
  handleEventName (e: any) {
    this.searchInfo.eventName = e.target.value
  }
  handleDeviceName (e: any) {
    this.searchInfo.deviceName = e.target.value
  }
  render () {
    const { columnDefs, current, total, rowData, pageSize, eventType, owner, status } = this.state
    return (
      <div className={styles['logbg']}>
        <div className={styles['main']}>
          <div className={styles['searchBoxWraper']}>
            <Row gutter={24} justify='center' className={styles['searchBox']}>
              <Col className={styles['ant-col-3']} span={3}>
                <div className='gutter-box'>
                  <Input placeholder='事件名称' onInput={this.handleEventName} onPressEnter={this.handleSearch} />
                </div>
              </Col>
              <Col className={styles['ant-col-3']} span={3}>
                <div className='gutter-box'>
                  <Input placeholder='设备名称' onInput={this.handleDeviceName} onPressEnter={this.handleSearch} />
                </div>
              </Col>
              <Col className={styles['ant-col-2']} span={2}>
                <div className='gutter-box'>
                  <Select
                    showSearch
                    placeholder='事件类型'
                    optionFilterProp='children'
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    className={styles['selctBox']}
                    onSelect={this.handleEventType}
                 >
                    {eventType.map((item, index) => {
                      return <Option value={item} key={index} className={styles['optionBox']}
                        title={item}>{item}</Option>
                    })}
                  </Select>
                </div>
              </Col>
              <Col className={styles['ant-col-2']} span={2}>
                <div className='gutter-box'>
                  <Select
                    showSearch
                    placeholder='负责人'
                    optionFilterProp='children'
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    className={styles['selctBox']}
                    onSelect={this.handleOwner}
                 >
                    {owner.map((item, index) => {
                      return <Option value={item} key={index} className={styles['optionBox']}
                        title={item}>{item}</Option>
                    })}
                  </Select>
                </div>
              </Col>
              <Col className={styles['ant-col-2']} span={2}>
                <div className='gutter-box'>
                  <Select
                    showSearch
                    placeholder='状态'
                    optionFilterProp='children'
                    filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                    className={styles['selctBox']}
                    onSelect={this.handleStatus}
                 >
                    {status.map((item, index) => {
                      return <Option value={item} key={index} className={styles['optionBox']}
                        title={item}>{item}</Option>
                    })}
                  </Select>
                </div>
              </Col>
              <Col className={styles['ant-col-2']} span={2} style={{ width: '28px' }}>
                <div className='gutter-box'>
                  <Button icon='search' onClick={this.handleSearch}></Button>
                </div>
              </Col>
            </Row>
          </div>
          <AgGrid {...{
            columnDefs,
            rowData
          }} />
          <Pagination current={current} pageSize={pageSize} total={total} onChange={this.onPageChange} />
        </div>
      </div>
    )
  }
}

export default EventLog
